#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on 2020-06-05

@author: zhuyu
"""
import os
import re
import time
import xlwt
import commands
import baseFunc


MEM_DIRS = '/Users/wangjianwen/Documents/rk3288Data/'


def getTotalPss(num):
    book = xlwt.Workbook(encoding='utf-8')
    # 创建一个名为sheetname的表单
    sheet = book.add_sheet('data')
    # # # 将工作簿以bookname命名并保存
    j = 0
    # 获取系统总内存
    sheet.write(0, 0, 'connect_momery')
    try:
        while j < num:
            lines = os.popen("adb shell dumpsys meminfo com.alipay.iot.connect").readlines()
            total = "TOTAL"
            for line in lines:
                if re.findall(total, line):  # 找到TOTAL 这一行
                    lis = line.split(" ")    # 将这一行，按空格分割成一个list
                    while '' in lis:         # 将list中的空元素删除
                        lis.remove('')
                    print lis[1]
                    usedram = int(lis[1])
            sheet.write(j + 1, 0, usedram)
            j = j + 1
    finally:
        book.save('{}osmemory_{}.xls'.format(MEM_DIRS, baseFunc.gettimestr()))

def dump_osmemory():
    mem_lines = os.popen('adb shell dumpsys meminfo').readlines()
    num = 0
    begin = False
    mem_count = 0
    for i in range(len(mem_lines)):
        if 'Total PSS by process' in mem_lines[i]:
            begin = True
            num = i
        if 'Total PSS by OOM adjustment' in mem_lines[i]:
            break
        if i > num and begin is True:
            if 'K' in mem_lines[i].split(':')[0].strip(' '):
                mem_count = mem_count + int(mem_lines[i].split(':')[0].strip(' ').strip('K').replace(',', ''))
    return mem_count


def proc_osmemory():
    mem_dict = {}
    mem_lines = commands.getoutput('adb shell cat /proc/meminfo')
    for mem in mem_lines.split('\n'):
        meminfo = mem.split(':')
        mem_dict[meminfo[0]] = meminfo[1].strip()
    time.sleep(2)
    return mem_dict


def getappmem():
    book = xlwt.Workbook(encoding='utf-8')
    # 创建一个名为sheetname的表单
    sheet = book.add_sheet('data')
    # # # 将工作簿以bookname命名并保存
    i = 1
    try:
        while i < 600:
            # plt.plot(0, getTotalPss(), '.')
            mem_data = int(getTotalPss())
            sheet.write(i, 0, mem_data)
            print str(i) + '-->' + str(mem_data)
            i = i + 1
    finally:
        book.save('{}xpaas_mem{}.xls'.format(MEM_DIRS, baseFunc.gettimestr()))


def getosmem(num):
    book = xlwt.Workbook(encoding='utf-8')
    # 创建一个名为sheetname的表单
    sheet = book.add_sheet('data')
    # # # 将工作簿以bookname命名并保存
    # 获取系统总内存
    sheet.write(0, 0, 'usedram')
    sheet.write(0, 1, 'available')
    j = 0
    try:
        while j < num:
            osm = proc_osmemory()
            memtotal = int(osm['MemTotal'].split(' ')[0])
            available = int(osm['MemAvailable'].split(' ')[0])
            usedram = memtotal - available
            sheet.write(j+1, 0, usedram)
            sheet.write(j+1, 1, available)
            print 'proc-{}: {}'.format(j, usedram)
            j = j + 1
    finally:
        book.save('{}osmemory_{}.xls'.format(MEM_DIRS, baseFunc.gettimestr()))


if __name__ == '__main__':
    # getosmem(300)
    print getTotalPss(1000)